package edu.dhbw.mannheim;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;



@SuppressWarnings("serial")
public class XMPPReceiverServlet extends HttpServlet {
	public static final Logger _log = Logger.getLogger(XMPPReceiverServlet.class.getName());
    public void doPost(HttpServletRequest req, HttpServletResponse res)
          throws IOException {
        XMPPService xmpp = XMPPServiceFactory.getXMPPService();
        Message message = xmpp.parseMessage(req);

        JID fromJid = message.getFromJid();
        String body = message.getBody();
        
        
        String msgBody = "Oh, who are you? :)\n You wrote me:\n" + body;
        Message msg = new MessageBuilder()
            .withRecipientJids(fromJid)
            .withBody(msgBody)
            .build();

        boolean messageSent = false;
        SendResponse status = xmpp.sendMessage(msg);
        messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
        
        if (!messageSent) {
        	_log.info("Message not sent back: "+fromJid.getId()+ ","+body);
        }
        
        
        
//        UserService userService = UserServiceFactory.getUserService();
//		User user = userService.getCurrentUser();
//
//		Key blogKey = KeyFactory.createKey("blog", "blogblogblog");
//		String topic = "Posted by XMPP";
//		Text content = new Text(fromJid.getId() + ": "+ body);
//		
//		Date date = new Date();
//		Entity post = new Entity("post", blogKey);
//		post.setProperty("user", user);
//		post.setProperty("date", date);
//		post.setProperty("topic", topic);
//		post.setProperty("content", content);
//
//		DatastoreService datastore = DatastoreServiceFactory
//				.getDatastoreService();
//		datastore.put(post);
    }
}
